﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.IO;
using Microsoft.Kinect;
using Microsoft.Win32;
using Kinect.Toolbox;
using Kinect.Toolbox.Gestures;
using Kinect.Toolbox.Voice; 
using System.Threading;
using System.Threading.Tasks;
using Kinect.Toolbox.Record;
using Microsoft.Speech.AudioFormat;
using Microsoft.Speech.Recognition;
using Kinectver1._0.CadObject;
using Kinectver1._0.openScad;
using SharpGL;
using SharpGL.WPF;
using SharpGL.Serialization;
using SharpGL.RenderContextProviders;
using SharpGL.SceneGraph;
using SharpGL.SceneGraph.Cameras;
using SharpGL.SceneGraph.Core;
using SharpGL.SceneGraph.Primitives;
using SharpGL.SceneGraph.Quadrics;
using SharpGL.OpenGLAttributes;
using SharpGL.Enumerations;

namespace Kinectver1._0
{

    public partial class MainWindow : Window
    {
        public KinectSensor glbSensor;
        const int skeletonCount = 6;
        Skeleton[] allSkeletons;
        readonly ColorStreamManager colorMan = new ColorStreamManager();
        readonly DepthStreamManager depthMan = new DepthStreamManager();
        SkeletonDisplayManager skelMan;
        readonly ContextTracker contextTracker = new ContextTracker();

        leftHandObserver leftHand;
        rightHandObserver rightHand;
        InitGesture InitGestureDetector;
        readonly AlgorithmicPostureDetector algorithmicPostureRecognizer = new AlgorithmicPostureDetector();


        private bool recordNextFrameForPosture;
        bool displayDepth;
        BindableNUICamera nuiCamera;

        public objectManager objMan = new objectManager();
        AudioClass audioMan;// = new AudioClass(glbSensor, InitGestureDetector);

        int count = 0;
        bool translate = false;
        bool rotate = false;
        bool scale = false;
        bool cube = false;
        bool square = false;
        bool cylinder = false;
        bool circle = false;
        bool sphere = false;
        bool constructed = false; //if the shape has been called
        bool conScale = false;
        bool conRotate = false;
        bool conTranslate = false;
        bool done = false;
        bool gestureinput = false;
        //stuff for booleanObj
        booleanObj bl;
        bool boolobj = false;
        bool is_union = false;
        bool is_diff = false;
        bool is_inter = false;
        bool isBool = false;
        bool select = false;
        bool stop = false;
        //input types needed

        //offObject tester = new offObject(@"C:\Users\DjEnjin\Desktop\e.off");
        //public cadObject selectedOne;
        //public cadObject selectedTwo;
        Vertex headCam = new Vertex();
        private static RecognizerInfo GetKinectRecognizer()
        {
            Func<RecognizerInfo, bool> matchingFunc = r =>
            {
                string value;
                r.AdditionalInfo.TryGetValue("Kinect", out value);
                return "True".Equals(value, StringComparison.InvariantCultureIgnoreCase) && "en-US".Equals(r.Culture.Name, StringComparison.InvariantCultureIgnoreCase);
            };
            return SpeechRecognitionEngine.InstalledRecognizers().Where(matchingFunc).FirstOrDefault();
        } 

        


        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
                //loading in kinect sensor to the first one
            try
            {
                KinectSensor.KinectSensors.StatusChanged += KinectSensors_StatusChanged;

                foreach (KinectSensor kinect in KinectSensor.KinectSensors)
                {
                    if (kinect.Status == KinectStatus.Connected)
                    {
                        glbSensor = kinect;
                        break;
                    }
                }
                if (KinectSensor.KinectSensors.Count == 0)
                    MessageBox.Show("No Kinect found");
                else
                    init();
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
            }
        }

        void KinectSensors_StatusChanged(object sender, StatusChangedEventArgs e)
        {

            switch (e.Status)
            {
                case KinectStatus.Connected:
                    if (glbSensor == null)
                    {
                        glbSensor = e.Sensor;
                        init();
                    }
                    break;
                case KinectStatus.Disconnected:
                    if (glbSensor == e.Sensor)
                    {
                        stopKinect(glbSensor);
                        MessageBox.Show("Kinect was disconnected");
                    }
                    break;
                case KinectStatus.NotReady:
                    break;
                case KinectStatus.NotPowered:
                    if (glbSensor == e.Sensor)
                    {
                        stopKinect(glbSensor);
                        MessageBox.Show("Kinect is no more powered");
                    }
                    break;
                default:
                    MessageBox.Show("Unhandled Status: " + e.Status);
                    break;
            }
        }
        //init
        private void init()
        {
            objMan.getSceneContainer(plane.objectsFolder); //link the scene to objman
            //objMan.addObject(tester);

            //Circle test = new Circle(new Vector3());

            //test.cObj.Transformation.ScaleX = 5;
            //test.cObj.Transformation.ScaleY = 5;

            //objMan.addObject(tester);

            //writeToScad();



            if (glbSensor == null)
                return;

            
            glbSensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
            glbSensor.ColorFrameReady += kinectRuntime_ColorFrameReady;
            /*
            glbSensor.DepthStream.Enable(DepthImageFormat.Resolution320x240Fps30);
            glbSensor.DepthFrameReady += kinectSensor_DepthFrameReady;
             */
            glbSensor.SkeletonStream.Enable(new TransformSmoothParameters
            {
                Smoothing = 0.2f,
                Correction = 0.2f,
                Prediction = 0.2f,
                JitterRadius = 0.02f,
                MaxDeviationRadius = 0.02f
            });
            glbSensor.SkeletonFrameReady += kinectRuntime_SkeletonFrameReady;
            glbSensor.SkeletonStream.TrackingMode = SkeletonTrackingMode.Seated;
            leftHand = new leftHandObserver();
            leftHand.gestureDectected += gestureDetected;
            leftHand.gesturesCanvas = gesturesCanvas;

            rightHand = new rightHandObserver();
            rightHand.gestureDectected += gestureDetected;
            rightHand.gesturesCanvas = gesturesCanvas;

            skelMan = new SkeletonDisplayManager(glbSensor, gesturesCanvas);
            glbSensor.Start();
            nuiCamera = new BindableNUICamera(glbSensor);
            //voice init
            

            colorCamera.DataContext = colorMan;
            InitGestureDetector = new InitGesture();
            InitGestureDetector.gestureDectected += gestureDetected;
            InitGestureDetector.add(leftHand);
            InitGestureDetector.add(rightHand);

            //audio init
 	        audioMan = new AudioClass(glbSensor, InitGestureDetector);
            //AudioSensor = KinectSensor.KinectSensors.FirstOrDefault(s => s.Status == KinectStatus.Connected);
            // was indented before ".firstOrDefault
            //testSCAD = new openSCAD();
 	        audioMan.speechRecognizer = audioMan.CreateSpeechRecognizer();
            audioMan.linkObj(objMan);
            //audioMan.link_list_view(objectViewer);
            audioMan.linkCoord_plane(plane);
            audioMan.loadInitialMenu(cmd, p1, p2, p3, num, numberbox); //initalizer, if you want text boxes to work too, setup something like this   

 	        audioMan.Start();
            
        }

        
        private void gestureDetected(string sgesture)
        {
            int pos = detectedGestureList.Items.Add(string.Format("{0} : {1}", sgesture, DateTime.Now));
            detectedGestureList.SelectedIndex = pos;
            if (sgesture == "SwipeToRight" && objMan.Objects.Count > 1 && !audioMan.is_Editing && !audioMan.is_Creating)
            {
                objMan.nextObject();
                /*
                if (objectViewer.SelectedIndex != 0)
                    objectViewer.SelectedIndex = objectViewer.SelectedIndex - 1;
                else
                    objectViewer.SelectedIndex = objectViewer.Items.Count - 1;*/
            }
            if (sgesture == "SwipeToLeft" && objMan.Objects.Count > 1 && !audioMan.is_Editing && !audioMan.is_Creating)
            {
                objMan.previousObject();
                /*
                if (objectViewer.SelectedIndex != objectViewer.Items.Count - 1)
                    objectViewer.SelectedIndex = objectViewer.SelectedIndex + 1;
                else
                    objectViewer.SelectedIndex = 0;*/
            }
            //testobjectpos(objMan); // show object position for testing. 
        }
        //self explainatory here
        void kinectSensorChooser1_KinectSensorChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            KinectSensor oldSensor = (KinectSensor)e.OldValue;
            stopKinect(oldSensor);
            KinectSensor newSensor = (KinectSensor)e.NewValue;
            glbSensor = newSensor;

        }

        //color camera
        void kinectRuntime_ColorFrameReady(object sender, ColorImageFrameReadyEventArgs e)
        {

            using (var frame = e.OpenColorImageFrame())
            {
                if (frame == null)
                    return;

                if (displayDepth)
                    return;

                colorMan.Update(frame);
            }
        }
        //depth sensor
        void kinectSensor_DepthFrameReady(object sender, DepthImageFrameReadyEventArgs e)
        {
            using (var frame = e.OpenDepthImageFrame())
            {
                if (frame == null)
                    return;

                if (!displayDepth)
                    return;

                depthMan.Update(frame);
            }
        }
        //skel camera
        void kinectRuntime_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {

            using (SkeletonFrame frame = e.OpenSkeletonFrame())
            {
                if (frame == null)
                    return;

                frame.GetSkeletons(ref allSkeletons);

                if (allSkeletons.All(s => s.TrackingState == SkeletonTrackingState.NotTracked))
                    return;

                ProcessFrame(frame);
            }
        }

        void ProcessFrame(ReplaySkeletonFrame frame)
        {
            Dictionary<int, string> stabilities = new Dictionary<int, string>();
            foreach (var skeleton in frame.Skeletons)
            {
                if (objMan.currentSelected != null)
                    scadtext.Text = objMan.currentSelected.toScad();


                if (skeleton.TrackingState != SkeletonTrackingState.Tracked)
                    continue;
                
                //context tracking
                //getCameraPoint(skeleton);
                contextTracker.Add(skeleton.Position.ToVector3(), skeleton.TrackingId);
                stabilities.Add(skeleton.TrackingId, contextTracker.IsStableRelativeToCurrentSpeed(skeleton.TrackingId) ? "Stable" : "Non stable");
                if (!contextTracker.IsStableRelativeToCurrentSpeed(skeleton.TrackingId))
                    continue;

                int handCount = 0;
                foreach (Joint joint in skeleton.Joints)
                {
                    if (joint.TrackingState != JointTrackingState.Tracked) //is it valid?
                        continue;

                    if (joint.JointType == JointType.HandRight)
                    {
                        rightHand.add(joint.Position, glbSensor);
                        handCount++;
                        /*
                        rightX.Text = joint.Position.X.ToString();
                        rightY.Text = joint.Position.Y.ToString();
                        rightZ.Text = joint.Position.Z.ToString();*/

                        
                    }
                    else if (joint.JointType == JointType.HandLeft)
                    {
                        leftHand.add(joint.Position, glbSensor);
                        handCount++;
                        /*
                        leftX.Text = joint.Position.X.ToString();
                        leftY.Text = joint.Position.Y.ToString();
                        leftZ.Text = joint.Position.Z.ToString();*/
                    }
                    else if (joint.JointType == JointType.Head)
                    {

                        if (plane.camReady == true)
                        {
                            headCam.Y = joint.Position.X * 10.0f;
                            headCam.X = joint.Position.Y * 10.0f;
                            headCam.Z = joint.Position.Z * 0.1f;
                            plane.Camera.Position = plane.CamPos + (headCam);
                        }
                    }
                    if (handCount == 2) //trugger two hand init
                    {
                        InitGestureDetector.trigger();

                        //the following should be placed into initGestureDetector, but for now, testing here
                        translate = audioMan.is_Translating;
                        rotate = audioMan.is_Rotating;
                        scale = audioMan.is_Scaling;
                        square = audioMan.is_Square;
                        circle = audioMan.is_Circle;
                        sphere = audioMan.is_Sphere;
                        cube = audioMan.is_Cube;
                        cylinder = audioMan.is_Cylinder;
                        boolobj = audioMan.is_Bool;
                        is_union = audioMan.is_union;
                        is_diff =  audioMan.is_difference;
                        is_inter = audioMan.is_intersection;
                        select = audioMan.is_Select;

                        gestureinput = audioMan.is_Gestures;


                        if (circle && constructed == false)
                        {
                            Circle cir = new Circle(new Vector3(0,0,0));
                            
                            objMan.addObject(cir);
                            constructed = true;
                        }
                        if (square && constructed == false)
                        {
                            Square sq = new Square(new Vector3(0, 0, 0));

                            objMan.addObject(sq);
                            constructed = true;
                        }
                        if (cube && constructed == false)
                        {
                            kCube cb = new kCube(new Vector3(0, 0, 0));

                            objMan.addObject(cb);
                            constructed = true;
                        }
                        if (cylinder && constructed == false)
                        {
                            kCylinder cy = new kCylinder(new Vector3(0, 0, 0));

                            objMan.addObject(cy);
                            constructed = true;
                        }
                        if (sphere && constructed == false)
                        {
                            kSphere sp = new kSphere(new Vector3(0,0,0));

                            objMan.addObject(sp);
                            constructed = true;
                        }

                        if (boolobj)
                        {
                            isBool = true;
                        }
                        
                        if(isBool && is_union == true && constructed == false)
                        {
                            bl = new booleanObj(1);
                            constructed = true;
                        }
                        
                        if (isBool && is_inter == true && constructed == false)
                        {
                            bl = new booleanObj(3);
                            constructed = true;
                        }

                        if(isBool && is_diff == true && constructed == false)
                        {
                            bl = new booleanObj(2);
                            constructed = true;
                        }

                        if (select && isBool && constructed)
                        {
                            bl.addShape(objMan.currentSelected);
                            cadObject tmp = objMan.currentSelected;
                            tmp.is_selected = true;
                            objMan.nextObject();
                            tmp.OFFobj.Material.Diffuse = System.Drawing.Color.FromName("Blue");

                            audioMan.is_Select = false;

                            //bl.toOff();
                            //objMan.addObject(bl);

                            //stop = true;
                        }


                        if (audioMan.is_Creating && constructed == true && audioMan.is_Gestures) //this means the object has been "made" but needs to be set, obj has been added to objman and currently selected
                        {
                            //the currently selected object should be displayed
                            //the lists should be conducted 
                            if (conScale == false)
                                objMan.currentSelected.doScale(InitGestureDetector.left, InitGestureDetector.right);
                            else if (conRotate == false)
                                objMan.currentSelected.doRotate(InitGestureDetector.left, InitGestureDetector.right);
                            else
                                objMan.currentSelected.doTranslate(InitGestureDetector.left, InitGestureDetector.right);
                        }

                        if (audioMan.is_Creating && constructed == true && audioMan.is_numb_edit && audioMan.is_finished) //this means the object has been "made" but needs to be set, obj has been added to objman and currently selected
                        {
                            //the currently selected object should be displayed
                            //the lists should be conducted 
                            if (count < 3)
                            {
                                if (count % 3 == 0)
                                    objMan.currentSelected.OFFobj.Transformation.ScaleX = Convert.ToSingle(audioMan.stored_audio_number);
                                if (count % 3 == 1)
                                    objMan.currentSelected.OFFobj.Transformation.ScaleY = Convert.ToSingle(audioMan.stored_audio_number);
                                if (count % 3 == 2)
                                    objMan.currentSelected.OFFobj.Transformation.ScaleZ = Convert.ToSingle(audioMan.stored_audio_number);

                                objMan.currentSelected.scale(objMan.currentSelected.OFFobj.Transformation.ScaleX, objMan.currentSelected.OFFobj.Transformation.ScaleY, objMan.currentSelected.OFFobj.Transformation.ScaleZ);
                            }
                            else if (count < 6)
                            {
                                if (count % 3 == 0)
                                    objMan.currentSelected.OFFobj.Transformation.RotateX = Convert.ToSingle(audioMan.stored_audio_number);
                                if (count % 3 == 1)
                                    objMan.currentSelected.OFFobj.Transformation.RotateY = Convert.ToSingle(audioMan.stored_audio_number);
                                if (count % 3 == 2)
                                    objMan.currentSelected.OFFobj.Transformation.RotateZ = Convert.ToSingle(audioMan.stored_audio_number);

                                objMan.currentSelected.rotate(objMan.currentSelected.OFFobj.Transformation.RotateX, objMan.currentSelected.OFFobj.Transformation.RotateY, objMan.currentSelected.OFFobj.Transformation.RotateZ);
                            }
                            else if(count < 9)
                            {
                                if (count % 3 == 0)
                                    objMan.currentSelected.OFFobj.Transformation.TranslateX = Convert.ToSingle(audioMan.stored_audio_number);
                                if (count % 3 == 1)
                                    objMan.currentSelected.OFFobj.Transformation.TranslateY = Convert.ToSingle(audioMan.stored_audio_number);
                                if (count % 3 == 2)
                                    objMan.currentSelected.OFFobj.Transformation.TranslateZ = Convert.ToSingle(audioMan.stored_audio_number);


                                objMan.currentSelected.translate(objMan.currentSelected.OFFobj.Transformation.TranslateX, objMan.currentSelected.OFFobj.Transformation.TranslateY, objMan.currentSelected.OFFobj.Transformation.TranslateZ);
                            }
                            audioMan.stored_audio_number = "";
                            count++;
                            
                            audioMan.is_finished = false;
                        }



                        ///////editing portion
                        if (audioMan.is_Editing && audioMan.is_Translating && audioMan.is_Gestures)
                        {
                            objMan.currentSelected.doTranslate(InitGestureDetector.left, InitGestureDetector.right);
                        }
                        if (audioMan.is_Editing && audioMan.is_Rotating && audioMan.is_Gestures)
                        {
                            objMan.currentSelected.doRotate(InitGestureDetector.left, InitGestureDetector.right);
                        }
                        if (audioMan.is_Editing && audioMan.is_Scaling && audioMan.is_Gestures)
                        {
                            objMan.currentSelected.doScale(InitGestureDetector.left, InitGestureDetector.right);
                        }

                        if (audioMan.is_Done) // this is a placeholder for cycling other editing functions, without changing the state of teh system
                        {
                            //
                            if (conScale == false)
                                conScale = true;
                            else if (conRotate == false)
                                conRotate = true;
                            else if (conTranslate == false)
                                conTranslate = true;

                            audioMan.is_Done = false;
                        }

                        if (audioMan.is_Set)
                        {
                            if (isBool)
                            {
                                bl.toOff();
                                objMan.addObject(bl);
                                List<cadObject> shapeList = new List<cadObject>();
                                foreach (cadObject obj in objMan.Objects)
                                {
                                    if (obj.is_selected)
                                    {
                                        foreach (var child in objMan.treeWrap.Children)
                                        {
                                            if (child.Name == obj.Name)
                                            {
        
                                                objMan.treeWrap.RemoveChild(child);
                                                break;
                                            }
                                        }
                           
                                        shapeList.Add(obj);                                        
                                   }
                                }

                                for (int i = 0; i < shapeList.Count; i++)
                                {
                                    objMan.removeObject(shapeList[i].Name);
                                }

                                
                                
                            }
                            count = 0;
                            boolobj = false;
                            isBool = false;
                            is_diff = false;
                            is_inter = false;
                            is_union = false;
                            constructed = false;
                            gestureinput = false;
                            conScale = false;
                            conRotate = false;
                            conTranslate = false;
                            audioMan.is_Set = false;
                            audioMan.is_Editing = false;
                            audioMan.is_set_cancel = false;
                            isBool = false;

                        }
                        if (audioMan.is_set_cancel == true)
                        {
                            //remove current selected if constructed
                            //if (constructed == true)
                            //{
                            //    workspacetree.Scene.SceneContainer.RemoveChild(objMan.currentSelected.OFFobj);
                            //    objMan.Objects.Remove(objMan.currentSelected);
                            //    objMan.currentSelected = objMan.Objects.Last<cadObject>();
                            //}

                            count = 0;
                            boolobj = false;
                            isBool = false;
                            is_diff = false;
                            is_inter = false;
                            is_union = false;
                            constructed = false;
                            gestureinput = false;
                            conScale = false;
                            conRotate = false;
                            conTranslate = false;
                            audioMan.is_Set = false;
                            audioMan.is_Editing = false;
                            isBool = false;
                            audioMan.is_set_cancel = false;
                        }

                        //if (translate)
                        //    tester.doTranslate(InitGestureDetector.left, InitGestureDetector.right);
                        //if (rotate)
                        //    tester.doRotate(InitGestureDetector.left, InitGestureDetector.right);
                        //if (scale)
                        //    tester.doScale(InitGestureDetector.left, InitGestureDetector.right);
                        
                        //if(onthefly)
                        //    tester.doTranslate(InitGestureDetector.left, InitGestureDetector.right);

                        handCount = 0;
                    }
                    //algorithmicPostureRecognizer.TrackPostures(skeleton);
                    //templatePostureDetector.TrackPostures(skeleton);
                    if (recordNextFrameForPosture)
                    {
                        //templatePostureDetector.AddTemplate(skeleton);
                        recordNextFrameForPosture = false;
                    }
                }
                //stabilitiesList.ItemsSource = stabilities;

            }
            //skelMan.Draw(frame.Skeletons, isSeated.IsChecked == true);


        }

        //manual loading of bytes, maybe load this into opengl at some point

        //private byte[] GenerateColoredBytes(DepthImageFrame depthFrame)
        //{
        //    short[] rawDepthData = new short[depthFrame.PixelDataLength];
        //    depthFrame.CopyPixelDataTo(rawDepthData);

        //    Byte[] pixels = new byte[depthFrame.Height * depthFrame.Width * 4]; //bgr32 emptybyte
        //    //bgra32 makes a transparent byte isntead of 


        //    //bgr index positins
        //    const int BlueIndex = 0;
        //    const int GreenIndex = 1;
        //    const int RedIndex = 2;

        //    //loop through distances
        //    for (int depthIndex = 0, colorIndex = 0; depthIndex < rawDepthData.Length && colorIndex < pixels.Length;
        //        depthIndex++, colorIndex += 4)
        //    {
        //        //get the player (requires skeleton tracking enabled)
        //        int player = rawDepthData[depthIndex] & DepthImageFrame.PlayerIndexBitmask;
                
        //        //gets the depth value
        //        int depth = rawDepthData[depthIndex] >> DepthImageFrame.PlayerIndexBitmaskWidth;

        //        //.9M or 2.65'
        //        if (depth <= 900)
        //        {
        //            pixels[colorIndex + BlueIndex] = 255;
        //            pixels[colorIndex + GreenIndex] = 0;
        //            pixels[colorIndex + RedIndex] = 0;
        //        }
        //        //.9m - 2m or 2.95' - 6.56'
        //        else if (depth >=900 && depth < 2000)
        //        {
        //            pixels[colorIndex + BlueIndex] = 0;
        //            pixels[colorIndex + GreenIndex] = 255;
        //            pixels[colorIndex + RedIndex] = 0;
        //        }
        //        //2m+  or 6.56' +
        //        else if (depth > 2000)
        //        {
        //            pixels[colorIndex + BlueIndex] = 0;
        //            pixels[colorIndex + GreenIndex] = 0;
        //            pixels[colorIndex + RedIndex] = 255;
        //        }

        //        //color players
        //        if (player > 0)
        //        {
        //            pixels[colorIndex + BlueIndex] = Colors.Gold.B;
        //            pixels[colorIndex + GreenIndex] = Colors.Gold.G;
        //            pixels[colorIndex + RedIndex] = Colors.Gold.R;
        //        }
        //        /*
        //        byte intestity = CalculateIntensity(depth);
        //        pixels[colorIndex + BlueIndex] = intestity;
        //        pixels[colorIndex + GreenIndex] = intestity;
        //        pixels[colorIndex + RedIndex] = intestity;*/
        //    }
        //    return pixels;
        //}
        /*
        public static byte CalculateIntensity(int distance)
        {
            return (byte)(255 - (255 * Math.Max(distance - MinDepthDistance, 0)
                / (MaxDepthDistanceOffset)));
        }*/
        void stopKinect(KinectSensor sensor)
        {
            if (sensor != null)
            {
                sensor.DepthFrameReady -= kinectSensor_DepthFrameReady;
                sensor.SkeletonFrameReady -= kinectRuntime_SkeletonFrameReady;
                sensor.ColorFrameReady -= kinectRuntime_ColorFrameReady;
                sensor.Stop();
                sensor.AudioSource.Stop();
                sensor = null;
            }
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            stopKinect(glbSensor); ;
        }

        private void reset_Click(object sender, RoutedEventArgs e)
        {
            detectedGestureList.Items.Clear();
        }



        public void writeToScad()
        {
            StreamWriter writer;

            if (File.Exists(@"C:\Program Files (x86)\KinectCAD\output.scad"))
            {
                writer = new StreamWriter(@"C:\Program Files (x86)\KinectCAD\output.scad");

                for (int i = 0; i < objMan.Objects.Count; i++)
                {
                    writer.Write(objMan.Objects[i].toScad());
                }

                writer.Close();
            }
            else if (File.Exists(@"C:\Program Files\KinectCAD\output.scad"))
            {
                writer = new StreamWriter(@"C:\Program Files\KinectCAD\output.scad");

                for (int i = 0; i < objMan.Objects.Count; i++)
                {
                    writer.Write(objMan.Objects[i].toScad());
                }

                writer.Close();
            }
            else
            {
                Directory.CreateDirectory(@"C:\Program Files (x86)\KinectCAD");
                File.Create(@"C:\Program Files (x86)\KinectCAD\output.scad");
            
                writer = new StreamWriter(@"C:\Program Files (x86)\KinectCAD\output.scad");

            for (int i = 0; i < objMan.Objects.Count; i++)
            {
                writer.Write(objMan.Objects[i].toScad());
            }

            writer.Close();
            }

            if (File.Exists(@"C:\Program Files (x86)\openSCAD\openscad.exe"))
            {
                Console.Write(@"C:\Program Files (x86)\openSCAD\openscad.exe");
                Console.Write("openscad -o " + @"C:\Program Files (x86)\KinectCAD\input.off " + @"C:\Program Files (x86)\KinectCAD\output.scad");
            }
            else if (File.Exists(@"C:\Program Files\openSCAD\openscad.exe"))
            {

            }
        }

        public void text1_TextChanged(object sender, TextChangedEventArgs e)
        {

        }
        


    }
}
